use chrono::Utc;
use once_cell::sync::Lazy;
use regex::Regex;
use validator::ValidationError;

pub fn current_date() -> chrono::NaiveDate {
    Utc::now().naive_local().date()
}

pub fn current_time() -> chrono::NaiveTime {
    Utc::now().naive_local().time()
}

pub fn current_datetime() -> chrono::NaiveDateTime {
    Utc::now().naive_local()
}

pub fn current_timestamp() -> chrono::DateTime<Utc> {
    Utc::now()
}

static RE_PHONE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[0-9-+()]{6,20}$").unwrap());

///  检查手机号码格式，长度在6～20之间，或者空
pub fn validate_phone(value: &str) -> Result<(), ValidationError> {
    if value.len() > 0 {
        if !RE_PHONE.is_match(value) {
            return Err(ValidationError::new("error phone format"));
        }
    }
    Ok(())
}

static RE_EMAIL: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$").unwrap());

/// 检查邮箱格式为`XXX@XXX.XXX`且长度小于64, 或者空
pub fn validate_email(value: &str) -> Result<(), ValidationError> {
    if value.len() > 0 {
        if value.len() > 64 || !RE_EMAIL.is_match(value) {
            return Err(ValidationError::new("error email format"));
        }
    }
    Ok(())
}
